import { forwardRef } from 'react';
import clsx from 'clsx';
import type { ButtonProps } from '@/types';
import styles from './Button.module.css';

/**
 * 通用按钮组件
 */
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
  (
    {
      children,
      className,
      variant = 'primary',
      size = 'medium',
      disabled = false,
      loading = false,
      icon,
      iconPosition = 'left',
      fullWidth = false,
      href,
      target,
      onClick,
      testId,
      ...props
    },
    ref
  ) => {
    // 构建 CSS 类名
    const buttonClasses = clsx(
      styles.button,
      styles[`button--${variant}`],
      styles[`button--${size}`],
      {
        [styles['button--disabled']]: disabled,
        [styles['button--loading']]: loading,
        [styles['button--full-width']]: fullWidth,
        [styles['button--icon-only']]: icon && !children,
      },
      className
    );

    // 按钮内容
    const buttonContent = (
      <>
        {loading && (
          <span className={styles.loadingSpinner} aria-hidden="true">
            <svg className={styles.spinner} viewBox="0 0 24 24">
              <circle
                className={styles.spinnerCircle}
                cx="12"
                cy="12"
                r="10"
                fill="none"
                strokeWidth="2"
              />
            </svg>
          </span>
        )}
        
        {icon && iconPosition === 'left' && !loading && (
          <span className={styles.icon} aria-hidden="true">
            {icon}
          </span>
        )}
        
        {children && (
          <span className={styles.content}>
            {children}
          </span>
        )}
        
        {icon && iconPosition === 'right' && !loading && (
          <span className={styles.icon} aria-hidden="true">
            {icon}
          </span>
        )}
      </>
    );

    // 如果有 href，渲染为链接
    if (href) {
      return (
        <a
          href={href}
          target={target}
          className={buttonClasses}
          data-testid={testId}
          aria-disabled={disabled}
          {...(props as any)}
        >
          {buttonContent}
        </a>
      );
    }

    // 渲染为按钮
    return (
      <button
        ref={ref}
        type="button"
        className={buttonClasses}
        disabled={disabled || loading}
        onClick={onClick}
        data-testid={testId}
        aria-busy={loading}
        {...props}
      >
        {buttonContent}
      </button>
    );
  }
);

Button.displayName = 'Button';

export default Button;
